from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import status, viewsets
from rest_framework.decorators import api_view
from rest_framework.response import Response
from snippets.models import Snippet, Department, maohao_info
from snippets.serializers import SnippetSerializer, DepartmentSerializer, maohao_infoSerializer


# class JSONResponse(HttpResponse):
#     """
#     An HttpResponse that renders its content into JSON.
#     """
#
#     def __init__(self, data, **kwargs):
#         content = JSONRenderer().render(data)
#         kwargs['content_type'] = 'application/json'
#         super(JSONResponse, self).__init__(content, **kwargs)
#
#
# @csrf_exempt
# def snippet_list(request):
#     """
#     列出所有的code snippet，或创建一个新的snippet。
#     """
#     if request.method == 'GET':
#         snippets = Snippet.objects.all()
#         serializer = SnippetSerializer(snippets, many=True)
#         return JSONResponse(serializer.data)
#
#     elif request.method == 'POST':
#         data = JSONParser().parse(request)
#         serializer = SnippetSerializer(data=data)
#         if serializer.is_valid():
#             serializer.save()
#             return JSONResponse(serializer.data, status=201)
#         return JSONResponse(serializer.errors, status=400)
# 包装（wrapping）API视图
# REST框架提供了两个可用于编写API视图的包装器（wrappers）。
#
# 用于基于函数视图的@api_view装饰器。
# 用于基于类视图的APIView类。
# 这些包装器提供了一些功能，例如确保你在视图中接收到Request实例，并将上下文添加到Response，以便可以执行内容协商。
#
# 包装器还提供了诸如在适当时候返回405 Method Not Allowed响应，并处理在使用格式错误的输入来访问request.data时发生的任何ParseError异常。
#
# 组合在一起
# 好的，我们开始使用这些新的组件来写几个视图。
#
# 我们在views.py中不再需要JSONResponse类了，所以把它删除掉。删除之后，我们就可以开始重构我们的视图了。
@api_view(['GET', 'POST'])
def snippet_list(request):
    """
    列出所有的snippets，或者创建一个新的snippet。
    """
    if request.method == 'GET':
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = SnippetSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# @csrf_exempt
# def snippet_detail(request, pk):
#     """
#     获取，更新或删除一个 code snippet。
#     """
#     try:
#         snippet = Snippet.objects.get(pk=pk)
#     except Snippet.DoesNotExist:
#         return HttpResponse(status=404)
#
#     if request.method == 'GET':
#         serializer = SnippetSerializer(snippet)
#         return JSONResponse(serializer.data)
#
#     elif request.method == 'PUT':
#         data = JSONParser().parse(request)
#         serializer = SnippetSerializer(snippet, data=data)
#         if serializer.is_valid():
#             serializer.save()
#             return JSONResponse(serializer.data)
#         return JSONResponse(serializer.errors, status=400)
#
#     elif request.method == 'DELETE':
#         snippet.delete()
#         return HttpResponse(status=204)
# 我们的实例视图比前面的示例有所改进。它稍微简洁一点，现在的代码与我们使用Forms API时非常相似。我们还使用了命名状态代码，这使得响应意义更加明显。
#
# 以下是views.py模块中单个snippet的视图。
@api_view(['GET', 'PUT', 'DELETE'])
def snippet_detail(request, pk):
    """
    获取，更新或删除一个snippet实例。
    """
    try:
        snippet = Snippet.objects.get(pk=pk)
    except Snippet.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = SnippetSerializer(snippet)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = SnippetSerializer(snippet, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


@api_view(['GET', 'POST'])
def Department_list(request):
    '''
    列出所有的Department，或者创建一个新的Department。
    '''
    if request.method == 'GET':
        Departments = Department.objects.all()
        serializer = DepartmentSerializer(Departments, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = DepartmentSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class DepartmentViewSet(viewsets.ModelViewSet):
    """
    允许用户查看或编辑的API路径。
    """
    queryset = Department.objects.all().order_by('-id')
    serializer_class = DepartmentSerializer


@api_view(['GET', 'PUT', 'DELETE'])
def Department_detail(request, pk):
    """
    获取，更新或删除一个Department实例。
    """
    try:
        Departments = Department.objects.get(pk=pk)
    except Department.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = DepartmentSerializer(Departments)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = DepartmentSerializer(Departments, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        Departments.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


@api_view(['GET', 'POST'])
def maohao_info_list(request):
    '''
    列出所有的 maohao_info，或者创建一个新的 maohao_info。
    '''
    if request.method == 'GET':
        maohao_infos = maohao_info.objects.all()
        serializer = maohao_infoSerializer(maohao_infos, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = maohao_infoSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class maohao_infoViewSet(viewsets.ModelViewSet):
    """
    允许用户查看或编辑的API路径。
    """
    queryset = maohao_info.objects.all().order_by('-id')
    serializer_class = maohao_infoSerializer


@api_view(['GET', 'PUT', 'DELETE'])
def maohao_info_detail(request, pk):
    """
    获取，更新或删除一个maohao_info实例。
    """
    try:
        maohao_infos = maohao_info.objects.get(pk=pk)
    except maohao_info.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = maohao_infoSerializer(maohao_infos)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = maohao_infoSerializer(maohao_infos, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        maohao_infos.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
